<template>
	<m-layout title="收银台" class="surePay" barBg="unset" color="#fff">
		<view class="main">
			<view class="top-msg">
				<view class="h2 ">
					<m-number :cny="item.wards != 4" unit="积分" :isOmit="false" :value="totalPrice" weight="600"
						size="68 36" color="#fff" />
					<m-text block color="#fff">已抵扣：{{item.couponAmt}}</m-text>
					<!-- <template v-for="(item3,idx) in item2">
						<view :key="idx" class="flex" v-if="item3.total>0">
							<m-text v-if="idx > 0 && idx < item2.length" spa="0 20" ftsize="30" weight="600"
								color="#fff"> +
							</m-text>
							<template v-if="item3.coinid == 1">
								
							</template>
							<template v-else>
								<m-number :value="item3.total" weight="600" :unit="Coin[item3.coinid]" size="68 36"
									color="#fff" />
							</template>
						</view>
					</template> -->
				</view>
				<m-block class="countdown flex-center" gap="14 0" bgColor="unset" radius="0">
					<text>剩余支付时间：</text>
					<uni-countdown :showDay="false" :showH="false" ref='countDowns' :timestamp="timestamp"
						:font-size="30" @timeup="timeOunt" :show-colon="false" />
				</m-block>
			</view>
			<!-- <template v-if="item2.length>1 || !isIntegral">
				<m-block gap="0 30" className="jf" spa="0 0 30 ">
					<template v-for="item3 in item2" v-if="item3.coinid!=1">
						<view :key="item3.coinid" class="jf-box flex">
							<m-icon :type="item3.coinid == 1?'ye':'jf'" wh="48"></m-icon>
							<view class="box flex-between">
								<text>可用{{Coin[item3.coinid]}}</text>
								<text>{{userbalance[item3.coinid]['balance']}}</text>
							</view>
						</view>
					</template>
				</m-block>
			</template> -->
			<payList ref="payList" class="pay-list" :filterArr="[12]" v-model="payType"></payList>
			<!-- <payType v-model="payType" ref="payList" class="pay-list"></payType> -->
		</view>
		<m-pay :loading="payLoading" class="pay-popop" title="请输入支付密码" v-model="payShow" :showCancel="true"
			@handleConfirm="propCreat" @handleCancel="payShow = false">
		</m-pay>
		<view class="btn-box">
			<view class="box">
				<m-button block @click="verify" :loading="payLoading">确认支付</m-button>
			</view>
		</view>
		<uni-popup ref="copyShow" type="center" :maskClick="false">
			<view class="copy-popup flex-column">
				<view class="center flex-center"><text>请确认支付是否已完成</text></view>
				<view class="copyShow-btn-box flex-between">
					<text @click="$refs.copyShow.close()">继续支付</text>
					<text
						@click="isOrder?Jump():Jump({url:'/pages/shopping/details/details?isPay=true&orderId=' + orderid,mode:2})">已完成支付</text>
				</view>
			</view>
		</uni-popup>

		<m-dialog class="bank-box" v-model="isShow" :loading="popupLoading" :showCancel="true"
			@handleConfirm="payConfirm" @handleCancel="isShow = false">
			<view class="top-bg flex-center">
				<m-icon type="popupbg" size="280"></m-icon>
			</view>
			<view class="dialog-box">
				支付确认短信已下发至手机，请注意查收
			</view>
			<view class="form-items flex">
				<m-formItem :isLine="false" placeholder="请输入短信验证码" v-model="phoneCode">
				</m-formItem>
			</view>
		</m-dialog>
	</m-layout>
</template>

<script>
	import { mapState } from 'vuex'
	import { First, CreatePayOrder } from '@/api/Order.js'
	import { gettime } from '@/api/Ctrls.js'
	import { balance } from '@/api/Users.js'
	export default {
		data() {
			return {
				isChecked: true,

				isOrder: false,
				payShow: false,
				payLoading: false,
				orderid: '',
				ordercode: '',
				item: {},
				item2: [],
				payMsg: {},
				payType: {
					payType: 3,
					type: 1 //1表示在线支付  2表示银行卡
				}, //默认余额支付
				payDebtType: 1, //债权积分		
				timestamp: -1, //倒计时

				popupLoading: false, //银行卡支付loading
				isShow: false,
				phoneCode: '', //短信验证
				payCode: '',
				payData: '',
			};
		},
		onLoad({ orderid, ordercode, isOrder }) {
			this.orderid = orderid || ordercode;
			this.isOrder = isOrder || false;
		},
		onShow() {
			this.getData();
		},
		computed: {
			...mapState({
				userbalance: state => state.user.userbalance,
				config: state => state.general.config,
				enum: state => state.general.enum,
			}),
			Coin() {
				return this.enum['Coin']
			},
			nowBalance() {
				try {
					return this.userbalance[1]['balance']
				} catch (e) {
					//TODO handle the exception
				}
				return 0
			},

			//计算总价  
			totalPrice() {
				try {
					return (this.item.totalCny || this.item.totalJf) - this.item.couponAmt
				} catch (e) {
					return 0.00
					//TODO handle the exception
				}
			},
			isIntegral() {
				let idx = this.item2.find(item => {
					return item.coinid == 1
				})
				if (!idx) {
					this.payType = {
						payType: 3,
						type: 1 //1表示在线支付  2表示银行卡
					}
				}
				return idx || false
			},
		},
		methods: {
			async verify() {
				if (!this.payType['payType']) {
					return this.Toast('请选择支付方式')
				}
				if (this.payType['type'] == 1) {
					if (this.payType['payType'] == 1) {
						if (this.nowBalance < this.totalPrice) {
							return this.Toast('账户余额不足')
						}
					}

					if ([1, 3].indexOf(Number(this.payType['payType'])) != -1) {
						this.payShow = true;
					} else {
						//直接创建
						this.creat();
					}
				}

			},
			//银行卡支付
			async payConfirm() {
				this.popupLoading = true;
				const { success, msg } = await payConfirm({
					smscode: this.phoneCode,
					merOrderId: this.payCode,
					hnapayOrderId: this.payData,
				})
				this.popupLoading = false;
				this.Toast(msg)

				if (success) {
					this.phoneCode = ''
					this.payCode = ''
					this.payData = ''
					this.isShow = false;
					await this.sleep(300)
					this.Jump({
						url: '/pages/shopping/details/details?orderId=' + this.orderid,
						mode: 3
					})
				}
			},
			//  创建 订单
			async creat(pwd = '') {
				try {
					const Paytype = Number(this.payType['payType']) //当前选择的支付类型
					const params = {
						paytype: Paytype,
						orderid: this.orderid,
						paypassword: pwd
					}
					this.payLoading = true;
					let res = {};
					console.log(params)
					const { success, data, msg } = await CreatePayOrder({
						...params,
						orderid: [this.orderid],
					})
					this.Toast(msg)
					try {
						if (success) {
							if ([1, 3].indexOf(Number(this.payType['payType'])) != -1) {
								this.payLoading = false;
							} else {
								const res = await this.payment(data)
								if (!res) return
							}
							await this.sleep(500)
							if (this.isOrder) {
								this.Jump()
							} else {
								this.Jump({
									url: '/pagesA/order/order',
									mode: 2
								})
							}
						} else {
							this.Toast(msg)
							this.payLoading = false;
						}
					} catch (e) {
						this.payLoading = false;
						//TODO handle the exception
					}

				} catch (e) {
					console.log(e)
					//TODO handle the exception
				}
			},
			//支付弹窗带入密码
			async propCreat({ pwd }) {
				this.paypassword = pwd;
				//关闭密码框
				this.payShow = false;
				this.creat(pwd);
			},
			// 倒计时
			async timeOunt() {
				console.log("结束")
				await this.sleep(500)
				console.log(this.timestamp)
				this.getData();
			},
			async gettime() {
				const { data } = await gettime()
				return data['timespan']
			},
			async getData() {
				await balance();
				let res = {}
				const { success, data, data2 } = await First({
					id: this.orderid
				})
				this.item = data;
				// this.item2 = data2.filter(item => {
				// 	return item.total > 0
				// });
				// for (let item2 in data2) {
				// 	const id = data2[item2]['coinid']
				// 	this.payMsg[id] = data2[item2]
				// }
				try {
					if (success) {
						//如果不是待支付订单  直接跳转
						if (this.item.state > 1) {
							setTimeout(() => {
								this.Jump({
									url: '/pages/shopping/details/details?orderId=' + this.orderid,
									mode: 3
								})
							}, 200)

						} else {
							if (this.item.state == 1) {
								try {
									let startTime = new Date(this.item.ctime);
									//设置结束时间
									let newTime = await this.gettime()
									let start = startTime.getTime() / 1000 + (30 * 60); // 结束秒数
									let end = start - newTime
									console.log('end',end)
									if (end <= 0) return
									this.timestamp = start - newTime;
								} catch (e) {
									console.log(e)
									//TODO handle the exception
								}

							}

							if (this.payLoading == true) {
								//当重新显示页面时   关闭支付弹窗 打开确认付款弹窗
								this.payLoading = false;
								this.payShow = false;
								this.$refs.copyShow.open()
							}
						}
						// const { data } = await gettime()
						// let endTime = Date.parse(data.timespan)
						// let startTime = Date.parse(data.timespan)
						// const timestamp = (endTime - startTime) / 1000
						// if (timestamp <= 0) return
						// this.timestamp = timestamp

					}
				} catch (e) {
					console.log(e)
					//TODO handle the exception
				}
			},
		},
	}
</script>

<style lang="scss">
	page {
		background: linear-gradient(0deg, var(--theme) 0%, #A592FF 100%) #f6f6f6 no-repeat;
		background-size: 750rpx 560rpx;
	}

	.bank-box {
		/deep/ .pay-box {
			padding: 0rpx !important;
			box-sizing: border-box;

			.form-items {

				padding: 0 30rpx 0rpx;

				.from-item {
					width: 100%;
					padding-left: 20rpx;
					width: 521rpx;
					background: #F6F6F6;
					border: 1px solid #D1D1D1 !important;
					border-radius: 15rpx;
				}
			}
		}

		/deep/ .dialog-footer {
			padding: 0 30rpx 0rpx;
		}

		.top-bg {
			width: 100%;
			height: 300rpx;
			background: linear-gradient(0deg, #F1F5FF 0%, #FFFFFF 100%);
			border-radius: 40rpx 40rpx 0rpx 0rpx;
		}

		.dialog-box {
			text-align: left;
			padding: 30rpx 30rpx;

			font-size: 30rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #333333;
		}
	}



	.surePay {
		.countdown {
			background: unset;

			text {
				font-size: 26rpx !important;
				font-family: PingFang SC-Regular, PingFang SC;
				font-weight: 400;
				color: #fff !important;
				padding-right: 5rpx;
			}

			/deep/ .uni-countdown {

				display: inline-flex !important;
				justify-content: center;
				align-items: center;



				.uni-countdown__number {
					line-height: unset !important;
					width: unset !important;
					display: inline !important;
					font-size: 26rpx !important;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #fff !important;
				}

				.uni-countdown__splitor {
					font-size: 28rpx !important;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #fff !important;
				}
			}
		}


		.top-msg {
			padding: 50rpx 0;
			text-align: center;

			.h1 {
				text-align: center;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #333333;
			}

			.h2 {
				padding: 20rpx 0;
				align-items: flex-end;

				.m-number {
					/deep/ .left-unit {
						font-size: 36rpx !important;
					}
				}


				.p2 {
					padding-left: 20rpx;
					padding-bottom: 20rpx;
					font-size: 64rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: var(--theme);
				}
			}


			.h4 {}
		}

		.jf {
			box-shadow: 0px 0px 10rpx 1px rgba(0, 0, 0, 0.06);

			.jf-box {
				padding: 24rpx 0;

				.box {
					flex: 1;
				}

				text:nth-of-type(1) {
					padding-left: 20rpx;
					font-size: 30rpx;
					font-family: SourceHanSansCN-Normal-, SourceHanSansCN-Normal;
					font-weight: normal;
					color: #1A1A1A;
				}

				text:nth-of-type(2) {
					font-size: 30rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #111;
				}
			}

			.jf-box+.jf-box {
				border-top: 1px solid #EEEEEE;
			}
		}


		.pay-type {
			padding-top: 50rpx;

			.titles {
				padding-bottom: 25rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #333333;
			}
		}

		.hint {
			padding: 50rpx 24rpx 20rpx;

			text {
				font-size: var(--fs_28);
				color: var(--text_1);
			}

			.yhxy {
				color: var(--theme);
			}
		}

		.btn-box {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;

			.box {
				margin-top: 24rpx;
				padding: 24rpx;
				background: #fff;
			}
		}

		.pay-popop {
			/deep/ .title {
				margin-bottom: 0;
			}
		}

		.copy-popup {
			width: 582rpx;
			height: 264rpx;
			background: #ffffff;
			border-radius: 20rpx;

			.center {
				flex: 1;
				font-size: 32rpx;
				font-family: PingFang SC;
				font-weight: bold;
				color: #333333;
			}

			.copyShow-btn-box {
				border-top: 1rpx solid #eeeeee;

				text {
					display: inline-block;
					flex: 1;
					text-align: center;
					padding: 26rpx 0;
					font-size: 26rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #666666;
				}

				text:nth-of-type(2) {
					border-left: 1rpx solid #eeeeee;
					color: #FF2323;
				}
			}
		}
	}
</style>